﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.Linq;

namespace WebHelper.Helpers
{
    [Serializable]
    public class XmlHelper
    {
        public static XElement CreateIfNotExist(XElement parent, params string[] names)
        {
            if (names != null)
            {
                for (int i = 0; i < names.Length; i++)
                {
                    if (parent.Element(names[i]) == null)
                    {
                        parent.Add(new XElement(names[i]));

                        //trace
                        Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "add Element:" + names[i], typeof(XmlHelper).Name + "  ");
                    }
                    parent = parent.Element(names[i]);
                }
            }
            return parent;
        }

        public static IEnumerable<XElement> GetElementsOfPath(XElement parent, params string[] names)
        {
            IEnumerable<XElement> ReturnedElements = null;
            if (names != null)
            {
                if(names.Length>0)
                {
                    ReturnedElements =parent.Elements(names[0]);
                }
                for (int i = 1; i < names.Length; i++)
                {
                    ReturnedElements = ReturnedElements.Elements(names[i]);
                }
            }
            return ReturnedElements;
        }

    }
}
